package zero.tech.games.logic.work.room;

import zero.tech.core.ZeroContext;
import zero.tech.core.data.Resp;
import zero.tech.core.event.service.api.EventService;
import zero.tech.core.work.QueueWork;
import zero.tech.core.work.WorkQueue;
import zero.tech.games.common.Code;
import zero.tech.games.logic.common.Room;
import zero.tech.games.logic.data.LogicEventType;
import zero.tech.games.logic.data.RoomStatus;
import zero.tech.games.logic.data.ServerData;
import zero.tech.games.logic.data.consts.LOGICCMD;
import zero.tech.games.logic.util.LogicUtil;
import zero.tech.wsnet.data.Message;

public class RoomTimerWork extends QueueWork{
	private Room room;
	@Override
	public void init(Object... objs) throws Exception {
		room=(Room) objs[0];
	}

	@Override
	public void run() {
		int room_status=room.getRoom_status();
		long now=System.currentTimeMillis();
		EventService eventService=ZeroContext.getInstance(EventService.class);
		if(ServerData.isClosed(room.getGame_id())) {
			if(room_status>RoomStatus.DEFAULT) {
				//房间关闭,强制解散房间
				eventService.engineNotify(LogicEventType.ROOM_DISSOLUTION_FREE, room);
			}else if(room_status==RoomStatus.DEFAULT) {
				LogicUtil.freeRoom(room,Message.build(LOGICCMD.RES_LEAVE, Resp.build(Code.OK, "强制离开成功")));
			}
			room.setRoom_status(RoomStatus.CLOSED);
			return;
		}
		if(room_status!=RoomStatus.DEFAULT&&room_status!=RoomStatus.CALCULATING) {
			boolean inDissolution=LogicUtil.inDissolution(room);
			if(inDissolution) {
				LogicUtil.autoAnswerDissolution(room);
				return;
			}
		}
		if(room_status==RoomStatus.DEFAULT) {
			if(room.getAllControllers().size()==0) {
				if(room.getNobody_time()==null) {
					room.setNobody_time(System.currentTimeMillis());
				}
				long nobody_time=room.getNobody_time();
				if(now-nobody_time>=1*60*1000) {
					//超过1分钟无人,则自动释放
					LogicUtil.freeRoom(room);
					return;
				}
			}else {
				room.setNobody_time(null);
			}
		}
		eventService.engineNotify(LogicEventType.ROOM_TIMER, room);
	}

	@Override
	public WorkQueue getWorkQueue() {
		return new WorkQueue() {
			@Override
			public long getId() {
				return room.getQueue_id();
			}
		};
	}

}
